import { listApps, getApps} from "@/api/app/apps";
import { fileServerUrl } from "@/config.js";
import {toast} from '@/utils/common'
import { getToken } from '@/utils/auth';


//检查app是否有版本更新
export function checkAppUpdate(flag){
  let param = {
	  appPackage: "com.chinacreator.qydums",
	  pageNum: 1,
	  pageSize: 10,
  }
  listApps(param).then(res=>{
	  let _this = this;
	  if(res.code == 200){
		  if(res.rows.length>0){
			  let row = res.rows[0];
			  let r = checkAppIsNew(plus.runtime.version, row.revision);
			  console.log(r)
			  if(r){
				  //有更新需要下载
				  uni.showModal({
					title: "更新提示",
					content:row.updatedContent,
					cancelText:"取消",
					confirmText:"确定",
					success(res) {
						if (res.confirm) {
							downLoadFile(row.appUrl);
						}
					}
				  })
			  }else{
				  if(flag){
					toast("已是最新版本");
				  }
			  }
		  }
	  }
  });
}
export function checkAppIsNew(currVer, newVer){
  console.log("currVer-"+currVer);
  console.log("newVer-"+newVer);
  let c = currVer.split(".");
  let n = newVer.split(".");
  if(n[0]>c[0]){
	  return true;
  }else{
	  if(n[1]>c[1]){
		  return true;
	  }else{
		  if(n[2]>c[2]){
			  return true;
		  }else{
			  return false;
		  }
	  }
  }
}
export function downLoadFile(url){
  console.log(fileServerUrl+url)
  uni.showLoading({
	title:"下载中..."
  })
  const downloadTask = uni.downloadFile({
	url: fileServerUrl+url,
	header:{Authorization: "Bearer " + getToken() },
	success: (res) => {
		console.log(JSON.stringify(res));
		uni.hideLoading();
		if (res.statusCode === 200) {
			console.log('下载成功');
			this.fileProcess = "100%";
			uni.openDocument({
				filePath:res.tempFilePath
			});
		}
	}
  });
  
  downloadTask.onProgressUpdate((res) => {
	this.fileProcess = res.progress;
	console.log('下载进度' + res.progress);
	console.log('已经下载的数据长度' + res.totalBytesWritten);
	console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
  
	// 满足测试条件，取消下载任务。
	if (res.progress > 50) {
	}
  });
}